package controllers;

import helpers.EncryptionClass;

import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.servlet.http.HttpSession;

import beans.LoginBeanRemote;
import beans.UserBeanRemote;
import dto.DTOUser;

/**
 * 
 * @author rusho
 * 
 */

@ManagedBean
public class SetProfileController {

	@EJB
	LoginBeanRemote pr;

	@EJB
	UserBeanRemote ubr;

	@ManagedProperty(value = "#{user}")
	DTOUser dtoUser;

	private String passwordCurrent;
	
	private String address;

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public SetProfileController() {

	}

	public DTOUser getDtoUser() {
		return dtoUser;
	}

	public void setDtoUser(DTOUser dtoUser) {
		this.dtoUser = dtoUser;
	}

	public String getPasswordCurrent() {
		return passwordCurrent;
	}

	public void setPasswordCurrent(String passwordCurrent) {
		this.passwordCurrent = passwordCurrent;
	}

	public void initializeDTOUser() {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(true);
		DTOUser dtoU = (DTOUser) session.getAttribute("dTOUser");

		dtoUser.setEmail(dtoU.getEmail());
		dtoUser.setId(dtoU.getId());
		dtoUser.setName(dtoU.getName());
		dtoUser.setPassword(dtoU.getPassword());
		dtoUser.setTelephone(dtoU.getTelephone());
		dtoUser.setType(dtoU.getType());

	}

	public boolean verifyPassword(String pass) {
		if (pass.equalsIgnoreCase((dtoUser.getPassword())))
			return true;
		return false;
	}

	public void setPasswordBean(int id, String pass) {
		pr.setPasswordBean(id, pass);

	}

	public void validatePassword(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {

		String passwordForm = (String) value;
		// internationalization
		HttpSession session = (HttpSession) FacesContext
				.getCurrentInstance().getExternalContext().getSession(true);
		LocaleController language = (LocaleController) session
				.getAttribute("language");
		String messageBundleName = "errorMessages.errors";
		if (language.getLanguage() == "ro") {
			messageBundleName += "_ro";
		} else if (language.getLanguage() == "hu") {
			messageBundleName += "_hu";
		} else if (language.getLanguage() == "de") {
			messageBundleName += "_de";
		}
		ResourceBundle messageBundle = ResourceBundle
				.getBundle(messageBundleName);
		// ////////
	
		
		/**
		 * @author soreas
		 * 
		 *         Encrypting password
		 */
		if(passwordForm.length()>0) {
		EncryptionClass encryptor = new EncryptionClass();
		String encryptedPasswordForm = encryptor.encryptPassword(passwordForm);
		
		System.out.println("Ecripted PAss " + encryptedPasswordForm);



		if (encryptedPasswordForm.length() > 0) {

			setPasswordCurrent(encryptedPasswordForm);

			initializeDTOUser();

			System.out.println("dtoUser este " + dtoUser.getName());
			System.out.println("dtoUser pass este" + dtoUser.getPassword());

			if (!verifyPassword(encryptedPasswordForm)) {
				FacesMessage message = new FacesMessage();
				message.setSeverity(FacesMessage.SEVERITY_ERROR);
				message.setSummary(messageBundle.getString("invalCurrentPass"));
				message.setDetail(messageBundle.getString("invalCurrentPass"));
				context.addMessage("setProfileForm:passwordFailed", message);
				throw new ValidatorException(message);
			}
			else if(verifyPassword(encryptedPasswordForm)){
				
			}
			
		}} else {
			FacesMessage message = new FacesMessage();
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			message.setSummary(messageBundle.getString("valueRequired"));
			message.setDetail(messageBundle.getString("valueRequired"));
			context.addMessage("setProfileForm:passwordFailed", message);
			throw new ValidatorException(message);
		}
	}

	public void validatePasswordNew(FacesContext context,
			UIComponent component, Object value) throws ValidatorException {

		UIInput passwordComponent = (UIInput) component.getAttributes().get(
				"password");

		String passwordForm = (String) passwordComponent.getValue();

		String confirm = (String) value;
		// internationalization
				HttpSession session = (HttpSession) FacesContext
						.getCurrentInstance().getExternalContext().getSession(true);
				LocaleController language = (LocaleController) session
						.getAttribute("language");
				String messageBundleName = "errorMessages.errors";
				if (language.getLanguage() == "ro") {
					messageBundleName += "_ro";
				} else if (language.getLanguage() == "hu") {
					messageBundleName += "_hu";
				} else if (language.getLanguage() == "de") {
					messageBundleName += "_de";
				}
				ResourceBundle messageBundle = ResourceBundle
						.getBundle(messageBundleName);
				// ////////
		
		initializeDTOUser();
		
		System.out.println("in validare parola este " + dtoUser.getPassword());

		/**
		 * @author soreas
		 * 
		 *         Encrypting password
		 */
		EncryptionClass encryptor = new EncryptionClass();
		String encryptedPasswordForm = encryptor.encryptPassword(passwordForm);
		String encryptedConfirm = encryptor.encryptPassword(confirm);

		if ((passwordForm.length() > 0) & (confirm.length() > 0)) {
			String current = dtoUser.getPassword();
			String name = dtoUser.getName();
			
			
			if (!encryptedPasswordForm.equals(encryptedConfirm)) {
				FacesMessage message = new FacesMessage();
				message.setSeverity(FacesMessage.SEVERITY_ERROR);
				message.setSummary(messageBundle.getString("passDontMatch"));
				message.setDetail(messageBundle.getString("passDontMatch"));
				context.addMessage("setProfileForm:passwordFailedNew", message);
				throw new ValidatorException(message);
			} else if (encryptedPasswordForm.equals(encryptedConfirm)
					 & verifyPassword(current) & (!verifyPassword(encryptedPasswordForm))
					 & (!passwordForm.equalsIgnoreCase(name))) {
				
				setPasswordBean(dtoUser.getId(), encryptedConfirm);
				dtoUser.setPassword(encryptedConfirm);
				
				address = "selectRepository.xhtml?faces-redirect=true";
				System.out.println("address:::"+address);
				FacesMessage message = new FacesMessage();
				message.setSeverity(FacesMessage.SEVERITY_ERROR);
				message.setSummary(messageBundle.getString("passChangedSucc"));
				message.setDetail(messageBundle.getString("passChangedSucc"));
				throw new ValidatorException(message);
				
			}
			else{
				FacesMessage message = new FacesMessage();
				message.setSeverity(FacesMessage.SEVERITY_ERROR);
				message.setSummary(messageBundle.getString("newPassMustBeDiff"));
				message.setDetail(messageBundle.getString("newPassMustBeDiff"));
				throw new ValidatorException(message);
			}
		} else {
			FacesMessage message = new FacesMessage();
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			message.setSummary(messageBundle.getString("valueRequired"));
			message.setDetail(messageBundle.getString("valueRequired"));
			context.addMessage("setProfileForm:passwordFailed", message);
			throw new ValidatorException(message);
		}

	}

	public String changePassword() {
		System.out.println("adresaaaa");
		return "success";

	}
	
	public String changeFirstPassword() {
		System.out.println("adresa"+address);
		return address;
	}

	public void validateEmail(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {

		String enteredEmail = (String) value;

		// internationalization
		HttpSession session = (HttpSession) FacesContext
				.getCurrentInstance().getExternalContext().getSession(true);
		LocaleController language = (LocaleController) session
				.getAttribute("language");
		String messageBundleName = "errorMessages.errors";
		if (language.getLanguage() == "ro") {
			messageBundleName += "_ro";
		} else if (language.getLanguage() == "hu") {
			messageBundleName += "_hu";
		} else if (language.getLanguage() == "de") {
			messageBundleName += "_de";
		}
		ResourceBundle messageBundle = ResourceBundle
				.getBundle(messageBundleName);
		// ////////
		
		if (enteredEmail.length() > 0) {
			Pattern p = Pattern
					.compile("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$");
			Matcher m = p.matcher(enteredEmail);
			boolean matchFound = m.matches();

			if (!matchFound) {
				FacesMessage message = new FacesMessage();
				message.setDetail(messageBundle.getString("email"));
				message.setSummary(messageBundle.getString("email"));
				throw new ValidatorException(message);
			} else {

				ubr.setEmailNew(dtoUser.getId(), enteredEmail);

				dtoUser.setEmail(ubr.getEmail(dtoUser.getId()));

			}
		}

		else {
			FacesMessage message = new FacesMessage();
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			message.setSummary(messageBundle.getString("valueRequired"));
			message.setDetail(messageBundle.getString("valueRequired"));
			context.addMessage("setProfileForm3:emailFailed", message);
			throw new ValidatorException(message);
		}
	}

	public void validatePhone(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		// TODO Auto-generated method stub

		String enteredPhone = (String) value;

		// internationalization
		HttpSession session = (HttpSession) FacesContext
				.getCurrentInstance().getExternalContext().getSession(true);
		LocaleController language = (LocaleController) session
				.getAttribute("language");
		String messageBundleName = "errorMessages.errors";
		if (language.getLanguage() == "ro") {
			messageBundleName += "_ro";
		} else if (language.getLanguage() == "hu") {
			messageBundleName += "_hu";
		} else if (language.getLanguage() == "de") {
			messageBundleName += "_de";
		}
		ResourceBundle messageBundle = ResourceBundle
				.getBundle(messageBundleName);
		// ////////
		
		if (enteredPhone.length() > 0) {
			Pattern p = Pattern.compile("^[0-9]{7,15}$");
			Matcher m = p.matcher(enteredPhone);
			boolean matchFound = m.matches();


			if (!matchFound) {
				FacesMessage message = new FacesMessage();
				message.setDetail(messageBundle.getString("phone"));
				message.setSummary(messageBundle.getString("phone"));
				throw new ValidatorException(message);
			}
			else{
				
				ubr.setPhoneNew(dtoUser.getId(), enteredPhone);
				dtoUser.setTelephone(ubr.getPhone(dtoUser.getId()));
			}

		} else {
			FacesMessage message = new FacesMessage();
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			message.setSummary(messageBundle.getString("valueRequired"));
			message.setDetail(messageBundle.getString("valueRequired"));
			context.addMessage("setProfileForm2:phoneFailed", message);
			throw new ValidatorException(message);
		}
	}

}
